<template>
  <!-- 分配权限的弹层 -->
  <el-dialog
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    :visible="showAssignDialog"
    @close="closeAssignDialog"
    @open="openDialog"
  >
    <!-- 权限点数据展示 -->
    <el-tree
      ref="tree"
      :data="permissionList"
      :props="{ label: 'name' }"
      :default-expand-all="true"
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <template #footer>
      <div style="text-align: right;">
        <el-button @click="closeAssignDialog">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { getPermissionListApi, assignPerm, getRoleDetailApi } from '@/api'
import transTree from '@/utils/transTree'
export default {
  props: {
    showAssignDialog: {
      type: Boolean
    },
    curId: {
      type: String,
      default: ''
    }

  },
  data() {
    return {
      permissionList: []
    }
  },
  methods: {
    // 关闭弹框
    closeAssignDialog() {
      this.$emit('close-assign-dialog')
      this.permissionList = []
    },
    // 弹框打开的时候发请求
    async openDialog() {
      const res = await getPermissionListApi()
      this.permissionList = transTree(res.data)
      // 根据id获取角色详情用于数据回显
      const resDetail = await getRoleDetailApi(this.curId)
      // console.log(resDetail)
      this.$refs.tree.setCheckedKeys(resDetail.data.permIds)
    },
    // 确定按钮执行的代码
    // {id:角色id, permIds:[] 所有选中的节点的id组成的数组}
    async confirm() {
      await assignPerm({
        id: this.curId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    }
  }
}
</script>
